<?php


namespace app\common\business;

use app\common\lib\Arr;
use app\common\model\mysql\Goods as GoodsModel;
use app\common\business\GoodsSku as GoodsSkuBis;
use think\Exception;
use think\facade\Cache;

class Goods extends BusBase
{
    public $model = NULL;
    public function __construct()
    {
        $this->model = new GoodsModel();
    }

    /**
     * 新增商品逻辑
     * @param $data
     * @return bool|null
     * @throws Exception
     */
    public function insertData($data){
        // 开启一个事务
        $this->model->startTrans();
        try {
            //dump($data);die;
            $goodsId = $this->add($data);
            if(!$goodsId){
                return $goodsId;
            }
            // 执行数据插入到sku表中
            // 统一规格
            if($data['goods_specs_type'] == 1){
                $goodsSkuData = [
                    "goods_id" => $goodsId,
                ];
                // 数据也要录入sku表一份，方便前台场频详情定位 待处理
                return true;
            } elseif ($data['goods_specs_type'] == 2) {// 多规格-电商核心
                $goodsSkuBisobj = new GoodsSkuBis();
                $data['goods_id'] = $goodsId;
                $res = $goodsSkuBisobj->saveAll($data);
                // $res = ""; // 模拟第二次插入失败测试事务
                if(!empty($res)){// 如果不为空
                    // 总库存
                    $stock = array_sum(array_column($res, "stock"));
                    // sku 表中的第一条或者最后一条数据部分字段
                    $goodsUpdateData = [
                        "price" => $res[0]['price'],
                        "cost_price" => $res[0]['cost_price'],
                        "stock" => $stock,
                        "sku_id" => $res[0]['id'],
                    ];
                    // 执行完毕之后，更新主表中的数据
                    $goodsRes = $this->model->updateById($goodsId, $goodsUpdateData);
                    // 随着商品库存变化采用消息队列形式更新库存
                    if(!$goodsRes){
                        throw new Exception("insertData:goods主表更新失败");
                    }
                }else{
                    throw new Exception("sku表新增失败");
                }
            }
            // 事务提交
            $this->model->commit();
        } catch (Exception $e) {
            // 记录日志
            // 事务回滚
            $this->model->rollback();
            return false;
        }
        return true;
    }

    /**
     * 获取分页列表的数据
     * @param $data
     * @param int $num
     * @return array
     */
    public function getLists($data, $num = 5){
        $likeKeys = [];// 不定义会报错
        if(!empty($data)){
            $likeKeys = array_keys($data);
        }
        try {
            $list = $this->model->getLists($likeKeys, $data, $num);
            $result = $list->toArray();
        } catch(Exception $e){
            $result = Arr::getPaginateDefaultData($num);
        }
        return $result;
    }

    public function getRotationChart(){
        $data = [
            'is_index_recommend' => 1,
        ];
        $field = "sku_id as id, title, big_image as image";
        try {
            $result = $this->model->getNormalGoodsByCondition($data, $field);
        } catch (Exception $e){
            return [];
        }
        return $result->toArray();
    }

    public function categoryGoodsRecommend($categoryIds){
        if(!$categoryIds){
            return [];
        }
        // 分类获取待完成 1,2,3,4,5 in category pid
        foreach($categoryIds as $k => $categoryId){
            $result[$k]["categorys"] = [];
        }
        foreach($categoryIds as $key => $categoryId){
            $result[$key]["goods"] = $this->getNormalGoodsFindInSetCategoryId($categoryId);
        }
        return $result;
    }

    public function getNormalGoodsFindInSetCategoryId($categoryId){
        $field = "sku_id as id, title, price, recommend_image as image";
        try {
            $result = $this->model->getNormalGoodsFindInSetCategoryId($categoryId, $field);
        } catch (Exception $e){
            return [];
        }
        return $result->toArray();
    }

    public function getNormalLists($data, $num, $order){
        try {
            $field = "sku_id as id, title, recommend_image as image, price";
            $list = $this->model->getNormalLists($data, $num, $field, $order);
            $res = $list->toArray();
            // 分页格式
            $result = [
                "total_page_num" => isset($res['last_page']) ? $res['last_page'] : 0,
                "count" => isset($res['total']) ? $res['total'] : 0,
                "page" => isset($res['current_page']) ? $res['current_page'] : 0,
                "page_size" => $num,
                "list" => isset($res['data']) ? $res['data'] : []
            ];
        } catch(Exception $e){
            // echo $e->getMessage();exit;
            return [];
        }
        return $result;
    }

    public function getGoodsDetailBySkuId($skuId){
        // sku_id sku表 => goods_id goods表->商品基本信息
        $skuBisObj = new GoodsSkuBis();
        $goodsSku = $skuBisObj->getNormalSkuAndGoods($skuId);
        if(!$goodsSku){
            return false;
        }
        if(empty($goodsSku['goods'])){
            return [];
        }
        // sku => sku数据
        $goods = $goodsSku['goods'];
        $skus = $skuBisObj->getSkusByGoodsId($goods['id']);
        if(!$skus){
            return [];
        }
        $flagValue = ""; // 标记哪个组合被选中
        foreach($skus as $sv){
            if($sv['id'] == $skuId){
                $flagValue = $sv["specs_value_ids"];
            }
        }
        $gids = array_column($skus, "id", "specs_value_ids");
        /*$gids = [];
        foreach($skus as $sku){
            $gids[$sku['specs_value_ids']] = $sku['id'];
        }*/
        if($goods['goods_specs_type'] == 1){
            $sku = [];
        } else {
            $sku = (new SpecsValue())->dealGoodsSkus($gids , $flagValue);
        }
        $result = [
            'title' => $goods['title'],
            "price" => $goodsSku['price'],
            "cost_price" => $goodsSku['cost_price'],
            "sales_count" => 0,
            "stock" => $goodsSku['stock'],
            "gids" => $gids,
            "image" => $goods['carousel_image'],
            "sku" => $sku,
            "detail" => [
                "d1" => [
                    "商品编码" => $goodsSku['id'],
                    "上架时间" => $goods['create_time'],
                ],
                // 正则处理图片路径
                "d2" => preg_replace('/(<img.+?src=")(.*?)/', '$1'.input('server.REQUEST_SCHEME') . '://' . request()->server('HTTP_HOST').'$2', $goods['description']),
            ],
        ];
        // 记录数据到Redis 作为商品PV统计
        Cache::inc("mall_pv_".$goods['id']);
        return $result;
    }
}
